#include "head.h"
/* Usage: */

int pipe_fd[2];
//status_t status;

void func(int num){
    write(pipe_fd[1], "1", 1);
}

int main(int argc, char *argv[])
{
    pipe(pipe_fd);
    if(fork()!=0){
        signal(2, func);
        wait(0);
        exit(0);
    }

    setpgid(0, 0);
    status_t status;
    initStatus(&status);
    printf("start!\n");    
    
    int skt_fd;
    getConfig();
    //printf("%s %s\n", ip, port);
    initSocket(&skt_fd, config->ip, config->port);
    int epl_fd = epoll_create(1);
    addEpoll(epl_fd, skt_fd);
    addEpoll(epl_fd, pipe_fd[0]);
    initMysql();
    pthread_mutex_lock(&status.db_lock);
    MYSQL *main_sql = getsql();
    pthread_mutex_unlock(&status.db_lock);
    if(!main_sql){
        printf("连接数据库失败！\n");
        close(skt_fd);
        return -1;
    }

    mkdir("./userDir", 0777);
    chdir("./userDir");
    while(1){
        struct epoll_event eves[CLINUM+2];
        int evenum = epoll_wait(epl_fd, eves, CLINUM+2, -1);

        for(int i=0; i<evenum; i++){
            if(eves[i].data.fd==pipe_fd[0]){
                char buf[60] = {0};
                read(pipe_fd[0], buf, sizeof(buf));
                pthread_mutex_lock(&status.lock);
                status.exit_flag = true;
                pthread_cond_broadcast(&status.cond);
                pthread_mutex_unlock(&status.lock);
                for(int i=0; i<THNUM; i++){
                    pthread_join(status.thds[i], NULL);
                }
                exit(0);
            }
            if(eves[i].data.fd==skt_fd){
                int net_fd = accept(skt_fd, NULL, NULL);
                client_status *user = log_or_re(net_fd, main_sql);
                if(!user){
                    printf("登录或注册失败！\n");
                    close(net_fd);
                    continue;
                }
                push(status.net_q, user);
                addEpoll(epl_fd, user->net_fd);
                printf("%d\n", user->islogin);
                printf("已于用户 %s 建立连接\n", user->user_name);
            }
            Node_t *t = status.net_q->head;
            while(t){
                client_status *user = t->data;
                printf("%s\n", user->user_id);
                if(eves[i].data.fd==user->net_fd){
                    work(user, &status);
                    if(user->islogin==false){
                        delEpoll(epl_fd, user->net_fd);
                        unlogin(user, user->net_fd);
                    }
                    break;
                }
                t = t->next;
            }
        }
    }
    return 0;
}
